"""用户管理模块视图"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions
from django.contrib.auth.models import User
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiParameter, OpenApiTypes
from apps.common.responses import (
    ApiResponseMixin,
    create_success_response_serializer,
    ValidationErrorResponseSerializer,
    UnauthorizedErrorResponseSerializer,
    ForbiddenErrorResponseSerializer,
    NotFoundErrorResponseSerializer,
    ConflictErrorResponseSerializer
)
from apps.common.pagination import StandardPagination
from .serializers import (
    UserListSerializer,
    UserDetailSerializer,
    UserCreateSerializer,
    UserUpdateSerializer,
    UserStatusSerializer,
    UserPasswordResetSerializer,
    BulkDeleteSerializer,
    BulkDeleteResultSerializer
)

@extend_schema_view(
    # 📋 获取用户列表
    list=extend_schema(
        summary="获取用户列表",
        description="获取用户列表，支持分页、搜索、过滤、排序。需要 auth.view_user 权限。",
        parameters=[
            OpenApiParameter(name='page', type=OpenApiTypes.INT, description='页码'),
            OpenApiParameter(name='page_size', type=OpenApiTypes.INT, description='每页数量'),
            OpenApiParameter(name='search', type=OpenApiTypes.STR, description='搜索关键词（用户名、邮箱、姓名）'),
            OpenApiParameter(name='is_active', type=OpenApiTypes.BOOL, description='是否激活'),
            OpenApiParameter(name='is_staff', type=OpenApiTypes.BOOL, description='是否为管理员'),
            OpenApiParameter(name='is_superuser', type=OpenApiTypes.BOOL, description='是否为超级用户'),
            OpenApiParameter(name='ordering', type=OpenApiTypes.STR, description='排序字段'),
        ],
     
    ),

    # 👤 获取用户详情
    retrieve=extend_schema(
        summary="获取用户详情",
        description="根据ID获取用户详细信息。需要 auth.view_user 权限。",
        responses={
            200: create_success_response_serializer(UserDetailSerializer, "获取成功", "Retrieve"),
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),

    # ➕ 创建用户
    create=extend_schema(
        summary="创建用户",
        description="创建新用户。需要 auth.add_user 权限。",
        responses={
            201: create_success_response_serializer(UserDetailSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
        }
    ),

    # ✏️ 完整更新用户
    update=extend_schema(
        summary="更新用户",
        description="完整更新用户信息（PUT方法）。需要 auth.change_user 权限。",
        responses={
            200: create_success_response_serializer(UserDetailSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),

    # 🔧 部分更新用户
    partial_update=extend_schema(
        summary="部分更新用户",
        description="部分更新用户信息（PATCH方法）。需要 auth.change_user 权限。",
        responses={
            200: create_success_response_serializer(UserDetailSerializer, "更新成功", "PartialUpdate"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),

    # 🗑️ 删除用户
    destroy=extend_schema(
        summary="删除用户",
        description="删除用户。需要 auth.delete_user 权限。",
        responses={
            204: None,  # 删除成功无返回内容
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class UserViewSet(ApiResponseMixin, viewsets.ModelViewSet):
    """
    用户管理ViewSet

    提供用户的CRUD操作和管理功能：
    - GET /users/ - 获取用户列表 (需要 auth.view_user 权限)
    - POST /users/ - 创建新用户 (需要 auth.add_user 权限)
    - GET /users/{id}/ - 获取用户详情 (需要 auth.view_user 权限)
    - PUT /users/{id}/ - 完整更新用户 (需要 auth.change_user 权限)
    - PATCH /users/{id}/ - 部分更新用户 (需要 auth.change_user 权限)
    - DELETE /users/{id}/ - 删除用户 (需要 auth.delete_user 权限)

    自定义操作：
    - POST /users/{id}/toggle_status/ - 激活/禁用用户
    - POST /users/{id}/reset_password/ - 重置用户密码
    - POST /users/{id}/toggle_staff/ - 设置管理员权限
    - POST /users/bulk_delete/ - 批量删除用户
    """

    queryset = User.objects.all().select_related().prefetch_related('groups', 'user_permissions')
    serializer_class = UserDetailSerializer  # 默认序列化器
    permission_classes = [IsAuthenticated, DjangoModelPermissions]  # 🔑 使用Django标准权限
    pagination_class = StandardPagination

    # 过滤、搜索、排序配置
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['is_active', 'is_staff', 'is_superuser', 'groups']
    search_fields = ['username', 'email', 'first_name', 'last_name']
    ordering_fields = ['date_joined', 'last_login', 'username', 'email']
    ordering = ['-date_joined']

    def get_queryset(self):
        """自定义查询集 - 优化查询性能"""
        queryset = super().get_queryset()
        # 预加载相关数据，避免N+1查询
        return queryset.select_related().prefetch_related('groups', 'user_permissions')

    def get_serializer_class(self):
        """根据action选择序列化器"""
        action_serializers = {
            'list': UserListSerializer,
            'create': UserCreateSerializer,
            'update': UserUpdateSerializer,
            'partial_update': UserUpdateSerializer,
            'retrieve': UserDetailSerializer,
        }
        return action_serializers.get(self.action, UserDetailSerializer)

    def perform_create(self, serializer):
        """创建用户时的额外处理"""
        user = serializer.save()
        # 记录创建日志
        print(f"用户 {self.request.user.username} 创建了新用户 {user.username}")

    def perform_update(self, serializer):
        """更新用户时的额外处理"""
        user = serializer.save()
        # 记录更新日志
        print(f"用户 {self.request.user.username} 更新了用户 {user.username}")

    def perform_destroy(self, instance):
        """删除用户时的额外处理"""
        # 防止删除超级用户
        if instance.is_superuser:
            from rest_framework.exceptions import PermissionDenied
            raise PermissionDenied("不能删除超级用户")

        # 防止删除自己
        if instance == self.request.user:
            from rest_framework.exceptions import PermissionDenied
            raise PermissionDenied("不能删除自己的账户")

        # 记录删除日志
        print(f"用户 {self.request.user.username} 删除了用户 {instance.username}")
        super().perform_destroy(instance)

    # 🔄 激活/禁用用户
    @extend_schema(
        summary="激活/禁用用户",
        description="激活或禁用用户账户。需要 auth.change_user 权限。",
        request=UserStatusSerializer,
        responses={
            200: create_success_response_serializer(UserDetailSerializer, "状态更新成功", "ToggleStatus"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['post'])
    def toggle_status(self, request, *args, **kwargs):
        """激活/禁用用户"""
        # 检查权限：需要 auth.change_user 权限
        if not request.user.has_perm('auth.change_user'):
            return self.error_response(
                message="没有权限执行此操作",
                code=403
            )

        user = self.get_object()
        serializer = UserStatusSerializer(data=request.data)

        if not serializer.is_valid():
            return self.error_response(
                message="参数验证失败",
                errors=serializer.errors,
                code=400
            )

        # 业务规则检查
        if user.is_superuser and not serializer.validated_data['is_active']:
            return self.error_response(
                message="不能禁用超级管理员账户",
                code=403
            )

        if user == request.user and not serializer.validated_data['is_active']:
            return self.error_response(
                message="不能禁用自己的账户",
                code=403
            )

        # 更新状态
        user.is_active = serializer.validated_data['is_active']
        user.save()

        user_data = UserDetailSerializer(user).data
        status_text = "激活" if user.is_active else "禁用"

        return self.success_response(
            data=user_data,
            message=f"用户{status_text}成功"
        )

    # 🔑 重置用户密码
    @extend_schema(
        summary="重置用户密码",
        description="重置用户密码。需要 auth.change_user 权限。",
        request=UserPasswordResetSerializer,
        responses={
            200: create_success_response_serializer(UserDetailSerializer, "密码重置成功", "ResetPassword"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['post'])
    def reset_password(self, request, *args, **kwargs):
        """重置用户密码"""
        # 检查权限：需要 auth.change_user 权限
        if not request.user.has_perm('auth.change_user'):
            return self.error_response(
                message="没有权限执行此操作",
                code=403
            )

        user = self.get_object()
        serializer = UserPasswordResetSerializer(data=request.data)

        if not serializer.is_valid():
            return self.error_response(
                message="参数验证失败",
                errors=serializer.errors,
                code=400
            )

        # 设置新密码
        user.set_password(serializer.validated_data['new_password'])
        user.save()

        user_data = UserDetailSerializer(user).data

        return self.success_response(
            data=user_data,
            message="密码重置成功"
        )

    # 👑 设置管理员权限
    @extend_schema(
        summary="设置管理员权限",
        description="设置用户的管理员权限。只有超级用户可以执行此操作。",
        request=None,
        responses={
            200: create_success_response_serializer(UserDetailSerializer, "权限设置成功", "ToggleStaff"),
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['post'])
    def toggle_staff(self, request, *args, **kwargs):
        """切换管理员权限"""
        # 检查权限：只有超级用户可以设置管理员权限
        if not request.user.is_superuser:
            return self.error_response(
                message="只有超级管理员可以设置管理员权限",
                code=403
            )

        user = self.get_object()

        # 业务规则检查
        if user == request.user and user.is_staff:
            return self.error_response(
                message="不能取消自己的管理员权限",
                code=403
            )

        # 切换管理员状态
        user.is_staff = not user.is_staff
        user.save()

        user_data = UserDetailSerializer(user).data
        status_text = "设置为管理员" if user.is_staff else "取消管理员权限"

        return self.success_response(
            data=user_data,
            message=f"{status_text}成功"
        )

    # 🗑️ 批量删除用户
    @extend_schema(
        summary="批量删除用户",
        description="根据ID列表批量删除用户。需要 auth.delete_user 权限。",
        request=BulkDeleteSerializer,
        responses={
            200: create_success_response_serializer(BulkDeleteResultSerializer, "批量删除成功", "BulkDelete"),
            400: ValidationErrorResponseSerializer,
            401: UnauthorizedErrorResponseSerializer,
            403: ForbiddenErrorResponseSerializer,
        }
    )
    @action(detail=False, methods=['post'])
    def bulk_delete(self, request):
        """批量删除用户"""
        # 检查权限：需要 auth.delete_user 权限
        if not request.user.has_perm('auth.delete_user'):
            return self.error_response(
                message="没有权限执行此操作",
                code=403
            )

        serializer = BulkDeleteSerializer(data=request.data)
        if not serializer.is_valid():
            return self.error_response(
                message="参数验证失败",
                errors=serializer.errors,
                code=400
            )

        ids = serializer.validated_data['ids']

        # 获取要删除的用户
        users_to_delete = self.get_queryset().filter(id__in=ids)

        # 业务规则检查
        superusers = users_to_delete.filter(is_superuser=True)
        if superusers.exists():
            return self.error_response(
                message="不能删除超级用户",
                code=403
            )

        if users_to_delete.filter(id=request.user.id).exists():
            return self.error_response(
                message="不能删除自己的账户",
                code=403
            )

        # 执行删除
        deleted_count = users_to_delete.count()
        users_to_delete.delete()

        return self.success_response(
            data={'deleted_count': deleted_count, 'deleted_ids': ids},
            message=f"成功删除 {deleted_count} 个用户"
        )
